﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Ym.Core.Service;
using System.Threading;
using System.Threading.Tasks;

namespace Ym.Core.Communi
{
    public class AsyncSerialPortService
    {
        SerialPortService serialPortService;
        IEnumerator<ISerialPortCommand> serialPortCommands;
        CancellationTokenSource cancellationTokenSource;
        Task task;
        public AsyncSerialPortService(SerialPortService serialPortService, IEnumerator<ISerialPortCommand> serialPortCommands)
        {
            this.serialPortService = serialPortService;
            this.serialPortCommands = serialPortCommands;
            this.cancellationTokenSource = null;
            this.task = null;
        }
        public void Start()
        {
            serialPortService.Open();
            cancellationTokenSource = new CancellationTokenSource();
            task = Task.Factory.StartNew(() =>
            {
                while (serialPortCommands.MoveNext())
                {
                    var read = serialPortService.WriteRead(serialPortCommands.Current.GetInput(), 3000);
                    var output = serialPortCommands.Current.GetOutput(read);
                    if (cancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }
                }
            }, cancellationTokenSource.Token);
        }

        public void End()
        {
            if (cancellationTokenSource == null)
            {
                return;
            }
            cancellationTokenSource.Cancel();
            Task.WaitAll(new Task[] { task });
            cancellationTokenSource = null;
            task = null;
            serialPortService.Close();
        }

        public void Dispose()
        {
            End();
        }
    }
}
